const fs = require('fs')
const FILE_PATH = "./dome.json"

// 查看所有
function findAll(callback){
    fs.readFile(FILE_PATH,"utf8",(err,date)=>{
        if(err){
            return callback(err)
        }
        return callback(null,JSON.parse(date).students)
    })
}

//根据id查看
function findstudentsbyid(id,callback){
    fs.readFile(FILE_PATH,'utf8',(err,date)=>{
        if(err){
           return  callback(err)
        }
        date = JSON.parse(date)
        let student = date.students.find(item=>{
            return item.id === id
        })
        callback(null,student)
    })
}

//添加
function add(student,callback){
    fs.readFile(FILE_PATH,"utf8",(err,date)=>{
        if(err){
            return callback(err)
        }
        date = JSON.parse(date)
        let id = date.students[date.students.length-1].id+1
        let stud = JSON.parse(student)
        stud.id = id
        date.students.push(stud)
        fs.writeFile(FILE_PATH,JSON.stringify(date),err=>{
            if(err){
                return callback(err)
            }
            callback(null)
        })
    })
}

//删除
function deletes(id,callback){
    fs.readFile(FILE_PATH,"utf8",(err,date)=>{
        if(err){
            return callback(err)
        }
        date = JSON.parse(date)
        let index = date.students.findIndex(item=>{
            return item.id === id
        })
        date.students.splice(index,1)
        fs.writeFile(FILE_PATH,JSON.stringify(date),err=>{
            if(err){
                return callback(err)
            }
            callback(null)
        })
    })
}

//更改
function changes(student,callback){
    fs.readFile(FILE_PATH,'utf8',(err,data)=>{
        if(err){
           return callback(err)
        }
        student = JSON.parse(student)
        student.id = Number(student.id)
        data = JSON.parse(data)
        let stu = data.students.find(item=>{
            return item.id === student.id
        })
        for (const key in student) {
            stu[key] = student[key]
        }
      fs.writeFile(FILE_PATH,JSON.stringify(data),(err)=>{
          if(err){
              return callback(err)
          }
          callback(null)
      })
    })
}
exports.findAll = findAll
exports.findstudentsbyid = findstudentsbyid
exports.add = add
exports.deletes = deletes
exports.changes = changes